package com.chr.controller;

import com.chr.constant.Constant;
import com.chr.entity.User;
import com.chr.entity.WechatUserUnionID;
import com.chr.service.UserService;
import com.chr.service.WeixinLoginService;
import com.chr.util.AesUtil;
import com.chr.util.DateUtil;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;

import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 第三方登录
 */
@Controller
public class LoginController {

    @Autowired
    private WeixinLoginService weixinLoginService;

    @Autowired
    private UserService userService;

    /**
     * qq登录 带参数发送服务器
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/qqLogin")
    public void qqLogin(HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回调
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/connect")
    public ModelAndView connect(HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        ModelAndView mav=new ModelAndView();
        mav.addObject("title","个人中心");
        mav.setViewName("myCenter");

        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken   = null,
                    openID        = null;
            long tokenExpireIn = 0L;

            if (accessTokenObj.getAccessToken().equals("")) {
//                我们的网站被CSRF攻击了或者用户取消了授权
//                做一些数据统计工作
                out.print("<script>alert('系统报错：没有获取到响应参数，请联系锋哥QQ：1002222344')</script>");
            } else {

                User user=new User();

                accessToken = accessTokenObj.getAccessToken();
               /* tokenExpireIn = accessTokenObj.getExpireIn();*/
/*

                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));
*/

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj =  new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();

                user.setOpenid(openID);
               /* out.println("欢迎你，代号为 " + openID + " 的用户!");
                request.getSession().setAttribute("demo_openid", openID);*/

                user.setType("qq登录");
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
              /*  out.println("<br/>");*/
                if (userInfoBean.getRet() == 0) {
                    user.setNickName(userInfoBean.getNickname());
                  /*  out.println(userInfoBean.getNickname() + "<br/>");
                    out.println(userInfoBean.getGender() + "<br/>");*/
                   /* out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL30() + "><br/>");
                    out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL50() + "><br/>");
                    out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL100() + "><br/>");*/
                    user.setUserImage(userInfoBean.getAvatar().getAvatarURL50());
                    // 先判断当前用户是否登录过
                    User dbUser = userService.findById(openID);
                    if(dbUser!=null){   // 假如登录过，获取用户的vip登记，然后修改其他信息
                        System.out.println("update");
                        user.setLevel(dbUser.getLevel());
                        user.setLastLoginDate(new Date());
                        userService.update(user);
                    }else{ // 假如没登录过，设置为普通vip权限 然后添加到数据库
                        System.out.println("add");
                        user.setLevel(Constant.LEVEL_COMMON);
                        user.setRegisterDate(new Date());
                        userService.add(user);
                    }


                    request.getSession().setAttribute("currentUser",user);

                    // out.println("<script>parent.reloadPage()</script>");
                } else {
                    out.println("<script>alert('系统出错： " + userInfoBean.getMsg()+"  请联系锋哥QQ：1002222344')</script>");
                }

            }
        } catch (QQConnectException e) {
        }
        return mav;
    }

    /**
     * 重定向到微信扫码登录地址
     * @return
     */
    @GetMapping("/weixinLogin")
    public String weixinLogin(){
        String url = weixinLoginService.genLoginUrl();
        return "redirect:"+url;
    }

    /**
     * 回调地址处理
     * @param code
     * @param state
     * @return
     */
    @GetMapping(value = "/weixinconnect")
    public ModelAndView weixinconnect(String code, String state,HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        String access_token=null;
        String openid=null;
        ModelAndView mav=new ModelAndView();
        mav.addObject("title","个人中心");
        mav.setViewName("myCenter");
        if (code != null && state != null) {
            // 验证state为了用于防止跨站请求伪造攻击
            String decrypt = AesUtil.decrypt(AesUtil.parseHexStr2Byte(state), AesUtil.PASSWORD_SECRET_KEY, 16);
            if (!decrypt.equals(Constant.PWD_MD5 + DateUtil.getYYYYMMdd())) {
                out.print("<script>alert('系统报错：没有获取到响应参数，请联系锋哥QQ：1002222344')</script>");
            }

            com.chr.entity.AccessToken access = weixinLoginService.getAccessToken(code);
            if (access != null) {
                User user=new User();
                // 把获取到的access_token和openId赋值给变量
                access_token=access.getAccess_token();
                openid=access.getOpenid();

                // 存在则把当前账号信息授权给扫码用户
                // 拿到openid获取微信用户的基本信息

                // 此处可以写业务逻辑

                WechatUserUnionID userUnionID = weixinLoginService.getUserUnionID(access_token,openid);
                /*mav.addObject("userInfo",userUnionID);*/
                user.setOpenid(userUnionID.getOpenid());
                user.setType("微信登录");
                user.setNickName(userUnionID.getNickname());
                user.setUserImage(userUnionID.getHeadimgurl());

               // out.println("<script>history.go(-1);reloadPage()</script>");

                // 先判断当前用户是否登录过
                User dbUser = userService.findById(openid);
                if(dbUser!=null){   // 假如登录过，获取用户的vip登记，然后修改其他信息
                    System.out.println("update");
                    user.setLevel(dbUser.getLevel());
                    user.setLastLoginDate(new Date());
                    userService.update(user);
                }else{ // 假如没登录过，设置为普通vip权限 然后添加到数据库
                    System.out.println("add");
                    user.setLevel(Constant.LEVEL_COMMON);
                    user.setRegisterDate(new Date());
                    userService.add(user);
                }

                request.getSession().setAttribute("currentUser",user);
            }
        }
        return mav;
    }

    /**
     * 用户注销
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/userLogout")
    public String userLogout(HttpServletRequest request, HttpServletResponse response)throws Exception{
        request.getSession().invalidate();
        return "redirect:/";
    }


}
